package com.common.weapp.service;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.common.user.properties.WePropertites;
import com.common.util.crypto.SHA1;


@Service
public class WeServiceImpl implements WeService {

	private Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private WePropertites wePropertites;
	
	 @Autowired  
	 private RestTemplate restTemplate; 

	@Override
	public boolean checkSignature(String timestamp, String nonce, String signature) {
		try {
			return SHA1.gen(wePropertites.getToken(), timestamp, nonce).equals(signature);
		} catch (Exception e) {
			logger.error("Checking signature failed, and the reason is :" + e.getMessage());
			return false;
		}
	}

	@Override
	public String getAccessToken() throws Exception {	
		
		Map<String, String> params = new HashMap<>();
	    params.put("appid", wePropertites.getAppid());
	    params.put("secret", wePropertites.getSecret());
	    params.put("grant_type", "client_credential");
	    
	    String accessToken = restTemplate.getForObject(GET_ACCESS_TOKEN_URL, String.class, params);
		
		return accessToken;
			
	}

}
